/*
 * Copyright (C) 2019. Uber Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lzy.okgo.harmony.autodispose.harmony;


import com.lzy.okgo.harmony.autodispose.harmony.internal.AutoDisposeHarmonyUtil;
import com.lzy.okgo.harmony.autodispose.harmony.internal.MainThreadDisposable;
import com.uber.autodispose.OutsideScopeException;
import io.reactivex.CompletableObserver;
import io.reactivex.CompletableSource;
import ohos.agp.components.Component;

final class DetachEventCompletable  implements CompletableSource {
  private final Component view;

  DetachEventCompletable(Component view) {
    this.view = view;
  }

  @Override
  public void subscribe(CompletableObserver observer) {
    Listener listener = new Listener(view, observer);
    observer.onSubscribe(listener);

    // Check we're on the main thread.
    if (!AutoDisposeHarmonyUtil.isMainThread()) {
      observer.onError(new IllegalStateException("Views can only be bound to on the main thread!"));
      return;
    }

    // Check that it's attached.
    boolean isAttached = view.isBoundToWindow()|| view.getTag() != null;
    if (!isAttached) {
      observer.onError(new OutsideScopeException("View is not attached!"));
      return;
    }

    view.setBindStateChangedListener(listener);
    if (listener.isDisposed()) {
      view.removeBindStateChangedListener(listener);
    }
  }

  static final class Listener extends MainThreadDisposable
      implements Component.BindStateChangedListener {
    private final Component view;
    private final CompletableObserver observer;

    Listener(Component view, CompletableObserver observer) {
      this.view = view;
      this.observer = observer;
    }



    @Override
    protected void onDispose() {
      view.removeBindStateChangedListener(this);
    }

    @Override
    public void onComponentBoundToWindow(Component component) {

    }

    @Override
    public void onComponentUnboundFromWindow(Component component) {
      if (!isDisposed()) {
        observer.onComplete();
      }
    }
  }
}
